<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        #id{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: aqua;
            left: 100px;
            top: 100px;
            
        }
    </style>
</head>
<body>
    <div id="id"></div>

    <script>
        let box = document.getElementById('id')
        box.onmousedown = function(e) {
            console.log(e);
            let distanceX = e.x - box.offsetLeft
            let distanceY = e.y - box.offsetTop

            document.onmousemove = function(ev) {
                let l = ev.x - distanceX
                let top = ev.y - distanceY

                if(l <= 0) {
                    left = 0
                }
                else if(l > document.documentElement.clientWidth - box.offsetWidth) {
                    left = document.documentElement.clientWidth - box.offsetWidth
                }

                if(top <= 0) {
                    top = 0
                }
                else if(top > document.documentElement.clientHeight - box.offsetTop) {
                    top = document.documentElement.clientHeight - box.offsetTop
                }
                box.style.left = l + 'px'
                box.style.top = top + 'px'
            }
        }
        
        box.onmouseup = function() {
            document.onmousemove = null
            document.onmousedown = null
        }
    </script>
</body>
</html>